package com.buerke.demoaidlservice;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = findViewById(R.id.btn_add);
        button.setOnClickListener(v -> add());

        initService();
    }

    IAdditionService mService;
    ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = IAdditionService.Stub.asInterface(service);
            System.out.println("aidl服务端 onServiceConnected --->>>");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    void initService() {
        Intent intent = new Intent(this, AdditionService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    public void add() {
        try {
            int result = mService.add(10, 5);
            System.out.println("result: " + result);
            Toast.makeText(MainActivity.this, "相加的方法为" + result, Toast.LENGTH_SHORT).show();
        } catch (RemoteException e) {
            throw new RuntimeException(e);
        }
    }
}